package com.hcy.app.screen.cipher

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.nfc.NfcAdapter
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.hcy.app.LocalNavController
import com.hcy.app.screen.nfc.NFCUtils
import com.hcy.app.screen.nfc.NfcHandler
import kotlinx.coroutines.launch


@Composable
fun Secret_Key_Page(viewModel: CipherViewModel=hiltViewModel()){
    val navController = LocalNavController.current
    val cipherState by viewModel.cipherState.collectAsState()
    var operation by remember { mutableStateOf(false) }
    var selected = remember { mutableStateListOf<Long>() }

    Box {
        Column(
            modifier = Modifier.systemBarsPadding().fillMaxSize().background(Color(0xFFE8E096))
        ) {
            // 工具栏
            Row(
                modifier = Modifier.fillMaxWidth().background(Color(0xFF8AECC9)),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                TextButton(
                    onClick = {
                        operation=!operation
                    },
                    content = { Text(text = if ( operation ) "取消" else "操作") },
                )
                IconButton(onClick = {
                    navController.navigate("cipher/home")
                }) {
                    Icon(
                        imageVector = Icons.Default.Home,
                        contentDescription = "首页",
                        modifier = Modifier.size(30.dp),
                        tint = Color.Black
                    )
                }
                Row {
                    if ( operation ){
                        TextButton(
                            onClick = {
                                viewModel.deleteNote(selected)
                                operation = !operation
                                selected.clear()
                            },
                            content = { Text(text = "删除") }
                        )
                    }else{
                        TextButton(
                            onClick = {
                                navController.navigate("cipher/secretForm/0")
                            },
                            content = { Text(text = "添加") }
                        )
                    }
                }
            }
            // 记录列表
            Column(
                modifier= Modifier.padding(top = 10.dp).weight(1f)
                    .verticalScroll(rememberScrollState())
            ){
                cipherState.secretList.forEach {
                    Secret_Item(
                        item=it,
                        isShow = operation,
                        modifier=Modifier.clickable{ navController.navigate("cipher/secretForm/${it.id}") },
                        checkCall = { checked->
                            if (checked)selected.add(it.id) else selected.remove(it.id)
                        }
                    )
                }
            }
        }
    }
}


@Composable
fun Secret_Item(item: SecretItem,isShow: Boolean, modifier: Modifier= Modifier,checkCall: (Boolean)->Unit){
    var checked by remember { mutableStateOf(false) }
    val lables = listOf<String>("记录1","记录2","记录3",)
    Surface(
        modifier = modifier.fillMaxWidth().padding(bottom = 10.dp),
        shape = RoundedCornerShape(10.dp)
    ) {
        Row {
            Column(
                modifier = modifier.weight(1f).padding(10.dp)
            ){
                Row {
                    Text(
                        text = item.remark,
                        maxLines = 1
                    )
                }
                Row {
                    Text(item.algorithm)
                    lables.forEach { it->
                        Text(it)
                    }
                }
            }
            if (isShow){
                Checkbox(
                    checked = checked,
                    onCheckedChange = {
                        checked=it
                        checkCall(checked)
                    }
                )
            }
        }
    }
}


@Preview
@Composable
fun Secret_Form_Pre(){
    Secret_Form()
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Secret_Form(viewModel: CipherViewModel= hiltViewModel(),keyId: Long=0){
    val context = LocalContext.current
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()

    var algorithm by remember { mutableStateOf(TextFieldValue("AES")) }
    var secretContent by remember { mutableStateOf(TextFieldValue("")) } // 用户可见的信息，aes-密钥，rsa-私钥
    var secretEx by remember { mutableStateOf("") } // 配合密钥使用的信息，aes-vi,rsa-公钥
    var secretKey by remember { mutableStateOf(TextFieldValue("")) }
    var prompt by remember { mutableStateOf(TextFieldValue("")) }
    var remark by remember { mutableStateOf(TextFieldValue("")) }

    var currentSecret by remember { mutableStateOf<SecretItem>(SecretItem(0,"","","","","",System.currentTimeMillis()/1000L,0)) }

    var bindNote by remember { mutableStateOf("未关联") }

    val isAdd = keyId ==0L

    LaunchedEffect(Unit){
        if (keyId !=0L){
            currentSecret = viewModel.getSecretDetail(keyId)
            var arr= currentSecret.content.split("-")
            if (arr.size==2){
                secretContent = TextFieldValue( arr[0] )
                secretEx = arr[1]
            }else{
                secretContent = TextFieldValue( "" )
                secretEx = ""
            }
            algorithm = TextFieldValue(currentSecret.algorithm)
            prompt = TextFieldValue(currentSecret.prompt)
            remark = TextFieldValue(currentSecret.remark)
            bindNote = viewModel.getBindNoteList(keyId).joinToString(",")
        }
    }

    val lifecycleOwner = LocalLifecycleOwner.current
//    var isNfcActive by remember { mutableStateOf(false) }
    val activity = remember { (context as? Activity) } // 仅在初始组合时获取
    val nfcHandler = remember { NfcHandler() }
    lateinit var nfcAdapter: NfcAdapter

    DisposableEffect(lifecycleOwner) {
        nfcAdapter = NfcAdapter.getDefaultAdapter(activity) // 初始化 nfcAdapter
        val observer = object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
//                isNfcActive = true
                nfcAdapter.enableReaderMode(
                    activity,
                    nfcHandler,
                    NfcAdapter.FLAG_READER_NFC_A,
                    null
                )
            }
            override fun onPause(owner: LifecycleOwner) {
//                isNfcActive = false
                nfcAdapter.disableReaderMode(activity)
            }
        }
        // 注册观察者
        lifecycleOwner.lifecycle.addObserver(observer)
        // 在 Composable 退出时移除观察者
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
    val nfcResult by nfcHandler.nfcResult.collectAsState()
    LaunchedEffect(nfcResult){
        Toast.makeText(context, "读取到数据：${nfcResult}", Toast.LENGTH_SHORT).show()
    }


    Column(
        modifier = Modifier.fillMaxSize().systemBarsPadding()
            .background(Color(0xFFF8F8F8))
    ) {
        Row {
            CenterAlignedTopAppBar(
                title = { Text(text = if (isAdd) "添加密钥" else "编辑密钥") },
                navigationIcon = {
                    IconButton(onClick = { navController.navigate("cipher/secret") }) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "",
                            tint = Color.Black
                        )
                    }
                },
            )
        }
        // 表单
        Surface {
            Column {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 10.dp)
                ) {
                    Text(text = "密钥算法：",fontWeight = FontWeight.Bold)
                    val options = listOf("AES-对称加密", "RSA-非对称加密", "SM4-国密")
                    var selectedOption by remember { mutableStateOf(options[0]) }
                    DropdownMenuExample(
                        options = options,
                        selectedOption = selectedOption,
                        onOptionSelected = { newOption ->
                            selectedOption = newOption
                            when(newOption){
                                "AES-对称加密" -> algorithm = TextFieldValue("AES")
                                "RSA-非对称加密" -> algorithm = TextFieldValue("RSA")
                                "SM4-国密" -> algorithm = TextFieldValue("SM4")
                            }
                        }
                    )
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 10.dp)
                ) {
                    Text(text = "密钥密码：",fontWeight = FontWeight.Bold)
                    OutlinedTextField(
                        value = secretKey,
                        onValueChange = {secretKey=it},
                        modifier = Modifier.weight(1f),
                    )
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 10.dp)
                ) {
                    Text(text = "密码提示：",fontWeight = FontWeight.Bold)
                    OutlinedTextField(
                        value = prompt,
                        onValueChange = {prompt=it},
                        modifier = Modifier.weight(1f),
                    )
                }
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 10.dp)
                ) {
                    Text(text = "备注信息：",fontWeight = FontWeight.Bold)
                    OutlinedTextField(
                        value = remark,
                        onValueChange = {remark=it},
                        modifier = Modifier.weight(1f),
                    )
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 10.dp)
                ) {
                    Text(text = "密钥信息：",fontWeight = FontWeight.Bold)
                    OutlinedTextField(
                        value = secretContent,
                        onValueChange = {secretContent=it},
                        modifier = Modifier.weight(1f),
                        maxLines = 1,
                        trailingIcon = {
                            Row(
                                modifier = Modifier.clickable{
                                    // 获取剪贴板服务
                                    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                                    // 创建ClipData对象
                                    val clip = ClipData.newPlainText("copied_text", secretContent.text)
                                    // 复制到剪贴板
                                    clipboard.setPrimaryClip(clip)
                                }
                            ) {
                                Icon(
                                    imageVector = Icons.Default.AccountCircle,
                                    contentDescription = "尾图标"
                                )
                                Text("复制")
                            }
                        },
                    )
                }

                Row {
                    Text(text = "关联文档：",fontWeight = FontWeight.Bold)
                    Text(text = bindNote)
                }
                Row {
                    Text(text = "密钥说明：",fontWeight = FontWeight.Bold)
                    Text(text = "1.密钥只做本地存储,删除无法恢复,RSA模式下NFC默认写入私钥！\n" +
                            "2.邮件或者短信等网络系统只会发送密文,需要配套的密钥才能还原内容！\n " +
                            "3.请通过物理法方式、或者其他你认为安全的方式交给值得信任的人!")
                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceAround
                ) {
                    Button(onClick = {
                        val (k1,k2) = clickRegenerateBtn(algorithm.text)
                        secretContent = TextFieldValue(k1)
                        secretEx = k2
                    }){
                        Text("重新生成")
                    }
                    Button(onClick = {
                        scope.launch {
                            currentSecret.prompt = prompt.text
                            currentSecret.remark = remark.text
                            currentSecret.conKey = secretKey.text
                            currentSecret.algorithm = algorithm.text
                            currentSecret.content = secretContent.text +"-"+secretEx.toString()

                            currentSecret.id = viewModel.saveSecretKey(currentSecret)
                            val li= viewModel.findSecretList()
                            Log.d(TAG,li.toString())
//                            navController.navigate("cipher/secret")
                        }
                    }){
                        Text("保存密钥")
                    }
                    Button(onClick = {
                        // 格式为：算法-密钥信息，使用时按-分割
                        val nfcMsg = "${algorithm.text}-${secretContent.text}"
                        val b= NFCUtils.writeDataToNfcTag(nfcHandler.currentTag.value,nfcMsg)
                        if (b){
                            Toast.makeText(context, "写入成功", Toast.LENGTH_SHORT).show()
                        }else{
                            Toast.makeText(context, "写入失败", Toast.LENGTH_SHORT).show()
                        }
                    }){
                        Text("写入NFC")
                    }
                }
            }
        }
    }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DropdownMenuExample(
    options: List<String>,
    selectedOption: String,
    onOptionSelected: (String) -> Unit // 回调函数
) {
    var expanded by remember { mutableStateOf(false) }
//    val options = listOf("AES-对称加密", "RSA-非对称加密", "SM4-国密")
//    var selectedOption by remember { mutableStateOf(options[0]) }

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = { expanded = it }
    ) {
        OutlinedTextField(
            value = selectedOption,
            onValueChange = {
            },
            readOnly = true,
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
            modifier = Modifier.menuAnchor().fillMaxWidth(),
        )

        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier.exposedDropdownSize() // 确保菜单宽度匹配文本字段
        ) {
            options.forEach { option ->
                DropdownMenuItem(
                    text = { Text(option) },
                    onClick = {
                        onOptionSelected(option) // 触发父组件的回调
                        expanded = false
                    }
                )
            }
        }
    }
}

fun clickRegenerateBtn(algorithm: String): Pair<String, String>{
    var key =Pair("","")
    when(algorithm){
        "AES" -> key=CryptUtilForAes.generate()
        "RSA" -> key=CryptUtilsForRsa.generate()
        "SM4" -> key=CryptUtilsForSm4.generate()
    }
    return key
}
